package subjectlist;

public class G如何求数组中两个元素的最小距离 {

    private static class 蛮力法{

        public static int minDistance(int[] arr,int num1,int num2){
            if (arr == null || arr.length <= 0) {
                System.out.println("参数不合理");
                return Integer.MIN_VALUE;
            }
            return 1;
        }
    }

    private static class 动态规划{
        public static int minDistance(int[] arr,int num1,int num2){
            if (arr == null || arr.length <= 0) {
                System.out.println("参数不合理");
                return Integer.MIN_VALUE;
            }

            int lastPos1=-1;//上次遍历到num1的位置
            int lastPos2=-1;//上次遍历到num2的位置
            int minDis=Integer.MIN_VALUE;//num1与num2的最小距离
            for (int i = 0; i < arr.length; ++i) {
                if (arr[i] == num1) {
                    lastPos1=i;
                    if (lastPos2 >= 0) {
                        minDis=Math.min(minDis,lastPos1-lastPos2);
                    }
                }
                if (arr[i] == num2) {
                    lastPos2=i;
                    if (lastPos1 >= 0) {
                        minDis=Math.min(minDis,lastPos2-lastPos1);
                    }
                }
            }
            return minDis;
        }
    }
}
